﻿using System;
using System.Data.SQLite;
using System.IO;
using System.Resources;

namespace UPos.Core.DataDriver
{
    class DbSQLite : IDisposable
    {
        static string DefaultConnectionString { get; set; }

        static DbSQLite()
        {
            //if (string.IsNullOrWhiteSpace(DefaultConnectionString))
            //{
            //    var setting = ConfigurationManager.ConnectionStrings["sqlite"];
            //    if (setting == null)
            //        throw new ConfigurationErrorsException("ConnectionString 配置节，必须至少包含一个名为 sqlite 的项");
            //    DefaultConnectionString = setting.Decode();
            //}

            CheckDbFile();
        }

        static void CheckDbFile()
        {
            string filename = "UPos.db3";
            if (!File.Exists(filename))
            {
                try
                {
                    ResourceManager rm = new ResourceManager("UPos.Core.Properties.Resources", typeof(DbSQLite).Assembly);
                    byte[] bytes = (byte[]) rm.GetObject("UPos");
                    using (var fs = File.Create("UPos.db3"))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

            DefaultConnectionString = "Data Source=UPos.db3;Version=3;";
        }

        SQLiteConnection CoreConn { get; set; }

        public DbSQLite()
        {
            CoreConn = new SQLiteConnection(DefaultConnectionString);
            CoreConn.Open();
        }

        internal object ExecuteScalar(string sql, params SQLiteParameter[] oracleParameters)
        {
            using (var cmd = CoreConn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(oracleParameters);
                return cmd.ExecuteScalar();
            }
        }

        internal SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] oracleParameters)
        {
            using (var cmd = CoreConn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(oracleParameters);
                return cmd.ExecuteReader();
            }
        }

        public void Dispose()
        {
            CoreConn.Dispose();
        }

        internal SQLiteCommand CreateCommand(string sqltext)
        {
            return new SQLiteCommand(sqltext, CoreConn);
        }
    }
}
